import React, { FC, useEffect } from 'react'
import { Form, Input, Button, Space } from 'antd'
import { QuestionTablePropsType } from './interface'
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'

const PropComponent: FC<QuestionTablePropsType> = (props: QuestionTablePropsType) => {
  const { title, columns, dataSource, onChange, disabled } = props
  const [form] = Form.useForm()

  useEffect(() => {
    form.setFieldsValue({ title, columns, dataSource })
  }, [title, columns, dataSource, form])

  function handleValuesChange() {
    if (onChange == null) return

    const newValues = form.getFieldsValue() as QuestionTablePropsType

    onChange(newValues)
  }

  return (
    <Form
      layout="vertical"
      initialValues={{ title, columns, dataSource }}
      form={form}
      onValuesChange={handleValuesChange}
      disabled={disabled}
    >
      <Form.Item label="标题" name="title" rules={[{ required: true, message: '请输入问卷标题' }]}>
        <Input />
      </Form.Item>
      <Form.Item label="列编辑">
        <Form.List name="columns">
          {(fields, { add, remove }) => (
            <>
              {fields.map(({ key, name }, index) => {
                return (
                  <Space key={key} align="baseline">
                    <Form.Item
                      name={[name, 'title']}
                      rules={[{ required: true, message: '请输入选项文字' }]}
                    >
                      <Input placeholder="输入选项文字..." />
                    </Form.Item>
                    <Form.Item
                      name={[name, 'dataIndex']}
                      rules={[{ required: true, message: '请输入选项文字' }]}
                    >
                      <Input placeholder="输入选项文字..." />
                    </Form.Item>
                    {index > 0 && <MinusCircleOutlined onClick={() => remove(name)} />}
                  </Space>
                )
              })}
              <Form.Item>
                <Button
                  type="link"
                  onClick={() => add({ text: '', value: '' })}
                  icon={<PlusOutlined />}
                  block
                >
                  添加选项
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
      </Form.Item>
    </Form>
  )
}

export default PropComponent
